﻿#include "TlvCodeWidget.h"
#include "stores/DataStroes.h"

TlvCodeWidget::TlvCodeWidget(QWidget *parent)
    : PageWidget(parent)
{
    initByDataStore();

    connect(this, &PageWidget::pageNameChanged, this, [=](int pageID, const QString& newName){
        panelAt(pageID)->setTitle(newName);
    });
}

TlvCodeWidget::~TlvCodeWidget()
{

}

TlvCodePanel *TlvCodeWidget::addPage(const QString &pageName)
{
    TlvCodePanel* panel = new TlvCodePanel(this);
    panel->setTitle(pageName);
    PageWidget::addPage(pageName, panel);
    return panel;
}

QList<CodePageModel> TlvCodeWidget::toCodesModel()
{
    QList<CodePageModel> res;
    for (int i = 0; i < pageCount(); i++) {
        res.push_back(panelAt(i)->toCodeModel());
    }
    DataStroes::instance()->tlvPrj()->model().data().codes = res;  // 保存到stores
    return res;
}

void TlvCodeWidget::initByDataStore()
{
    auto& model = DataStroes::instance()->tlvPrj()->model();
    QString prjPath = DataStroes::instance()->tlvPrj()->latestProject();
    if (model.isValid()) {  // 数据可用，渲染所有代码页
        TlvPrjModel& data = model.data();
        for (CodePageModel& page : data.codes) {
            TlvCodePanel* panel = addPage(page.title);
            panel->setCode(page.code);
        }
        if (data.cmds.length() > 0) setPage(0);
    } else {  // 数据不可用，添加20行空白表格
        addPage("Page 1");
        setPage(0);
    }
}

TlvCodePanel *TlvCodeWidget::panelAt(int pageID)
{
    return qobject_cast<TlvCodePanel*>(PageWidget::panelAt(pageID));
}

void TlvCodeWidget::onAddClicked()
{
    addPage(tr("New Code"));
}
